package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: taft
 * @Date: 2018-12-18 12:01
 */
@Service
public class UploadService {

    Logger logger = LoggerFactory.getLogger(UploadService.class);

    @Autowired
    private FastFileStorageClient storageClient;

    public String uploadImage(MultipartFile file) {

        try {
            Set<String> allowExt = new HashSet<>();
            allowExt.add("image/jpeg");
            allowExt.add("image/png");
            allowExt.add("image/jpg");

            //判断文件，后缀  8+3规范  exe,txt,doc,jpg,java,

            String contentType = file.getContentType();

            if (!allowExt.contains(contentType)) {

                logger.info("哥们你的后缀有问题，只能上传.jpg和.png,你的后缀为{}", contentType);
                return null;
            }

            //判断文件，内容,imageIO用来读取图片，

            BufferedImage read = ImageIO.read(file.getInputStream());

            if (null == read) {
                logger.info("文件内容有误，请上传真正的图片");
                return null;
            }

            //IO保存文件

            String name = file.getOriginalFilename();

            String ext = StringUtils.substringAfterLast(name, ".");

            //使用fastDfs的客户端实现上传
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);

            return "http://image.leyou.com/" + storePath.getFullPath();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
